package net.asfun.jvalog.domain;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.Query;

import net.asfun.jvalog.po.Web;
import net.asfun.jvalog.service.Jdoer;
import net.asfun.jvalog.service.JdoerFactory;
import net.asfun.jvalog.task.UpdateManager;
import net.asfun.jvalog.view.PagerInfo;

public class Link {

	private Web web;
	
	public Link(){
		web = new Web();
	}
	
	private Link(Web web){
		this.web = web;
	}
	
	public static Link load(Long id) {
		Jdoer<Web> dba = JdoerFactory.getWebJdo();
		return new Link(dba.load(id));
	}
	
	public void save() {
		Jdoer<Web> dba = JdoerFactory.getWebJdo();
		dba.save(web);
		UpdateManager.enableCacheTask();
	}
	
	public void setUrl(String url) {
		web.setUrl(url);
	}
	
	public String getUrl() {
		return web.getUrl();
	}
	
	public String getTitle() {
		return web.getTitle();
	}
	
	public void setTitle(String title) {
		web.setTitle(title);
	}
	
	public void setImage(String url) {
		web.setImage(url);
	}
	
	public String getImage() {
		return web.getImage();
	}
	
	public void setDescription(String description) {
		web.setDescription(description);
	}
	
	public String getDescription() {
		return web.getDescription();
	}
	
	public Long getId() {
		return web.getKey().getId();
	}
	
	public void update() {
		UpdateManager.enableCacheTask();
	}

	public static List<Link> listAll(PagerInfo pager) {
		List<Link> list = new ArrayList<Link>();
		Jdoer<Web> dba = JdoerFactory.getWebJdo();
		pager.setTotal(dba.all().size() - 1);
		Query query = dba.prepareQuery();
		query.setFilter("flag > -1");
		query.setRange(pager.getStart(), pager.getEnd());
		Collection<Web> clt = dba.more(query);
		for(Web web : clt) {
			list.add(new Link(web));
		}
		return list;
	}

	public void setFlag(int flag) {
		if ( flag < 0 ) {
			flag = 0;
		}
		web.setFlag(flag);
	}
	
	public int getFlag() {
		return web.getFlag();
	}

	public static void remove(Long id) {
		Jdoer<Web> dba = JdoerFactory.getWebJdo();
		dba.delete(dba.load(id));
		UpdateManager.enableCacheTask();
	}

	public static List<Link> listRoll() {
		List<Link> list = new ArrayList<Link>();
		Jdoer<Web> dba = JdoerFactory.getWebJdo();
		Collection<Web> clt = dba.more("flag > 0");
		for(Web web : clt) {
			list.add(new Link(web));
		}
		return list;
	}
}
